﻿using NLog;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WinAppWeChartDemo.Common;
using WinAppWeChartDemo.Models;

namespace WinAppWeChartDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private WeChartHelper chartHelper = new WeChartHelper();
        private Logger logger = LogManager.GetCurrentClassLogger();

        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Initialized(object sender, EventArgs e)
        {
            chartHelper.AddToQueueEvent += AddToQueueEvent;
            SendMessageJob.WriteLogEvent += Write;
            //启动定时任务
            ReportJobScheduler.Start();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //停止定时任务
            ReportJobScheduler.Shutdown();
        }

        public void Bt_start_Click(object sender, RoutedEventArgs e)
        {
            SendMessageModel model = new SendMessageModel
            {
                appid = tb_appid.Text,
                appsecret = tb_appsecret.Text,
                openid = tb_openid.Text,
                template_id = tb_template_id.Text,
                message = tb_message.Text
            };
            chartHelper.AddMessage(model);
        }

        private void AddToQueueEvent(SendMessageModel model)
        {
            string msg = $"添加到队列完成：AppID：{model.appid},OpenId:{model.openid},Message:{model.message}";
            logger.Info(msg);
            Write(msg);
        }

        private void Write(string log)
        {
            lv_log.Dispatcher.Invoke(() =>
            {
                lv_log.Items.Add(log);
                if (!lv_log.IsFocused)
                {
                    lv_log.SelectedIndex = lv_log.Items.Count - 1;
                    lv_log.ScrollIntoView(lv_log.SelectedItem);
                }
            });
        }
    }
}
